package com.hyt.it.ogt.pj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.pj.common.MarkException;
import com.hyt.it.ogt.pj.common.ResponseCode;
import com.hyt.it.ogt.data.Constants;
import com.hyt.it.ogt.pj.feign.KwClient;
import com.hyt.it.ogt.pj.mapper.SubjectMapper;
import com.hyt.it.ogt.pj.model.entity.Subject;
import com.hyt.it.ogt.pj.service.ISubjectService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * <p>
 * 评卷科目表 服务实现类
 * </p>
 *
 * @author qiaozj
 * @since 2020-07-09
 */
@Service
public class SubjectServiceImpl extends BaseServiceImpl<SubjectMapper, Subject> implements ISubjectService {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private KwClient kwClient;

    @Autowired
    private SubjectMapper subjectMapper;

    /**
     * 初始化评卷科目
     *
     * @param projectId 评卷项目id
     */
    @Override
    public void initSubject(String projectId) {
        // 1、拉取科目信息
        ApiResponse<List<Subject>> res = kwClient.getSubjects(projectId, null);
        logger.info(">>>拉取到的评卷科目数据:{}", JSONObject.toJSONString(res));
        List<Subject> kwSubjects = res.getData();
        if (CollectionUtils.isEmpty(kwSubjects)) {
            throw new MarkException(ResponseCode.INIT_PROJECT_NO_SUBJECT.toString());
        }
        // 2、保存科目信息
        for (Subject subject : kwSubjects) {
            String subjectId = subject.getSubjectId();
            if (StringUtils.isEmpty(subjectId)) {
                continue;
            }
            Subject projectSubject = subjectMapper.selectByProjectIdAndSubjectId(projectId, subjectId);
            if (projectSubject == null) {
                subject.setId(null);
                subject.setSubjectId(subjectId);
                save(subject);
            } else {
                // 有个考生数量，需要更新
                subject.setId(projectSubject.getId());
                subject.setSubjectId(subjectId);
                updateById(subject);
            }
        }
    }

    /**
     * 根据评卷项目id查询科目
     *
     * @param projectId
     * @return
     */
    @Override
    public List<Subject> selectByProjectId(String projectId) {
        List<Subject> subjects = subjectMapper.selectByProjectId(projectId);
        return subjects;
    }

    /**
     * 在多科目且没有选择科目的情况下，获取还有评卷任务的科目作为评卷科目
     *
     * @param projectId 评卷项目id
     * @return 评卷科目
     */
    @Override
    public Subject getMarkSubject(String projectId) {
        return subjectMapper.getMarkSubject(projectId);
    }

    /**
     * 更新科目评完状态
     *
     * @param projectId 评卷项目id
     * @param subjectId 评卷科目
     * @param isFinish  是否评完
     */
    @Override
    public void updateSubjectMarkStatus(String projectId, String subjectId, Boolean isFinish) {
        subjectMapper.updateSubjectMarkStatus(projectId, subjectId, isFinish);
    }

    @Override
    public void saveSubject(String projectId, List<Subject> subjects) {
        for (Subject subject : subjects) {
            String subjectId = subject.getSubjectId();
            if (StringUtils.isEmpty(subjectId)) {
                continue;
            }
            Subject projectSubject = this.lambdaQuery()
                    .eq(Subject::getProjectId, projectId)
                    .eq(Subject::getSubjectId, subjectId)
                    .eq(Subject::getDelFlag, false)
                    .one();
            if (projectSubject == null) {
                subject.setId(null);
                subject.setSubjectId(subjectId);
                saveSubject(subject);
            } else {
                // 有个考生数量，需要更新
                subject.setId(projectSubject.getId());
                subject.setSubjectId(subjectId);
                updateById(subject);
            }
        }
    }

    private void saveSubject(Subject subject) {
        try {
            save(subject);
        } catch (Exception e) {
            Throwable cause = e.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException) {
                String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
                if (Constants.SQLSTATE_23000.equals(sqlState)) {
                    logger.error("科目表中已存在主键为：【{}】的数据，sqlState：{}", subject.getProjectId() + "_" + subject.getSubjectId(), sqlState);
                }
            } else {
                throw e;
            }
        }
    }
}
